package com.wyx.rtddels.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wyx.rtddels.domain.RtdTag;
import com.wyx.rtddels.domain.dto.ExportDomain;
import com.wyx.rtddels.domain.dto.ExportFileDomain;
import com.wyx.rtddels.domain.dto.responsedto.ExportReqJsonBean;
import com.wyx.rtddels.mapper.RtdTagMapper;
import com.wyx.rtddels.service.ExportService;
import com.wyx.rtddels.util.HttpUtils;
import lombok.SneakyThrows;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

/**
 * @author WYX
 * @date 2024/12/3
 * @Description 导出接口实现逻辑
 */
@Service
public class ExportServiceImpl implements ExportService {


    /**
     * 导出名称
     */
    @Value("${export.name}")
    String name;

    /**
     * 路径地址
     */
    @Value("${export.path}")
    String path;

    @Value("${export.url}")
    String url;

    @Autowired
    RtdTagMapper rtdTagMapper;

    @Autowired
    HttpUtils httpUtils;

    /**
     * 导出csv文件
     */
    @Override
    @SneakyThrows
    public void ExportCsv() {
        FileInputStream fileInputStream = new FileInputStream(path);
        //文件
        List<ExportDomain> list = EasyExcel.read(fileInputStream).head(ExportDomain.class).excelType(ExcelTypeEnum.CSV).sheet().doReadSync();
        list.forEach(k -> {
            //处理逻辑
            System.out.println(k.getTagName());
            String tagName = k.getTagName();
            LambdaQueryWrapper<RtdTag> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RtdTag::getTag, tagName);
            RtdTag rtdTag = rtdTagMapper.selectOne(wrapper);
            String json = createJson(rtdTag);
            System.out.println(json);
            String filename= rtdTag.getTag()+".csv";
            httpUtils.getOut(url, json,filename);

        });
    }






    /**
     * 组装json字符串
     *
     * @param rtdTag
     * @return
     */
    public String createJson(RtdTag rtdTag) {
        ExportReqJsonBean exportReqJsonBean = new ExportReqJsonBean();
        //写入测点的编号进行组装json
        exportReqJsonBean.setTag(rtdTag.getId())
                .setExport(true)
                .setPageNum(1)
                .setPageSize(20)
                //转化到毫秒  2024-07-01 09:24:44 开始
                .setStime(1719797084000L)
                .setEtime(System.currentTimeMillis());
        return JSONUtil.toJsonStr(exportReqJsonBean);
    }


}
